from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Team, TeamMember, TeamSprint, SprintRecord, TeamTask, TeamRanking
from .serializers import TeamSerializer, TeamMemberSerializer, TeamRankingSerializer
from django.db import models
from django.utils import timezone
from django.db.models import Q
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError


class TeamViewSet(viewsets.ModelViewSet):
    """团队视图集"""
    serializer_class = TeamSerializer
    permission_classes = []

    def get_queryset(self):
        queryset = Team.objects.all()
        filter_type = self.request.query_params.get('filter_type', 'all')
        user_id = self.request.query_params.get('user_id')
        
        if user_id:
            if filter_type == 'mine':
                queryset = queryset.filter(creator=user_id)
            elif filter_type == 'joined':
                queryset = queryset.filter(teammember__user_id=user_id)

        return queryset.prefetch_related('teammember_set').select_related('creator')

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['request'] = self.request
        return context

    def perform_create(self, serializer):
        team = serializer.save()
        # 创建者自动成为成员
        TeamMember.objects.create(
            team=team,
            user_id=team.creator_id,
            role='creator'
        )

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        
        # 处理返回数据，添加额外信息
        data = serializer.data
        user_id = request.query_params.get('user_id')
        if user_id:
            user_id = int(user_id)
            for item in data:
                # 获取团队成员信息
                team_members = TeamMember.objects.filter(team_id=item['id']).select_related('user')
                members_info = [{
                    'id': member.user.id,
                    'username': member.user.username,
                    'avatar': f"https://api.dicebear.com/7.x/avataaars/svg?seed={member.user.username}",
                    'role': member.role
                } for member in team_members]
                
                item['members'] = members_info
                item['member_count'] = len(members_info)
                item['is_member'] = any(m['id'] == user_id for m in members_info)
                item['is_creator'] = item['creator'] == user_id

        return Response(data)

    def get(self, request):
        """获取团队列表"""
        user_id = request.GET.get('user_id')
        list_type = request.GET.get('type', 'all')  # 'all', 'my', 'discover'
        
        # 基础查询
        teams = Team.objects.all()
        
        if list_type == 'my' and user_id:
            # 获取我的团队（我创建的或我参加的）
            teams = teams.filter(
                models.Q(creator_id=user_id) |
                models.Q(teammember__user_id=user_id)
            ).distinct()
        elif list_type == 'discover' and user_id:
            # 获取可加入的团队（排除我已经加入的）
            teams = teams.exclude(
                models.Q(creator_id=user_id) |
                models.Q(teammember__user_id=user_id)
            )
        
        # 添加成员数量过滤
        teams = teams.annotate(
            member_count=models.Count('teammember', distinct=True)
        ).filter(member_count__lt=models.F('max_members'))
        
        serializer = TeamSerializer(teams, many=True)
        return Response(serializer.data)

    def post(self, request):
        """创建团队"""
        try:
            data = request.data.copy()
            creator_id = data.get('user_id')
            
            if not creator_id:
                return Response(
                    {'error': '缺少创建者ID'},
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            # 构建团队数据
            team_data = {
                'name': data.get('name'),
                'description': data.get('description'),
                'category': data.get('category'),
                'level': data.get('level'),
                'max_members': int(data.get('maxMembers', 5)),
                'creator': int(creator_id)  # 确保是整数
            }
            
            serializer = TeamSerializer(data=team_data)
            if serializer.is_valid():
                team = serializer.save()
                # 自动将创建者添加为团队成员
                TeamMember.objects.create(
                    team=team,
                    user_id=creator_id,
                    role='creator'
                )
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            
            return Response(
                {'error': serializer.errors},
                status=status.HTTP_400_BAD_REQUEST
            )
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_400_BAD_REQUEST
            )

    def put(self, request, team_id):
        """更新团队信息"""
        try:
            team = Team.objects.get(id=team_id)
            serializer = TeamSerializer(team, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Team.DoesNotExist:
            return Response(
                {"error": "Team not found"}, 
                status=status.HTTP_404_NOT_FOUND
            )

    def delete(self, request, team_id):
        """删除团队"""
        try:
            team = Team.objects.get(id=team_id)
            team.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except Team.DoesNotExist:
            return Response(
                {"error": "Team not found"}, 
                status=status.HTTP_404_NOT_FOUND
            )

class TeamMemberView(APIView):
    """团队成员视图"""
    permission_classes = []

    def get(self, request, team_id=None):
        """获取团队成员列表"""
        if team_id:
            members = TeamMember.objects.filter(team_id=team_id)
        else:
            members = TeamMember.objects.all()
        
        serializer = TeamMemberSerializer(members, many=True)
        return Response(serializer.data)

    def post(self, request, team_id):
        """添加团队成员"""
        user_id = request.data.get('user')
        
        # 检查是否已经是成员
        if TeamMember.objects.filter(team_id=team_id, user_id=user_id).exists():
            raise ValidationError({'error': '已经是团队成员'})
            
        # 检查团队是否已满
        team = Team.objects.get(id=team_id)
        current_members = TeamMember.objects.filter(team_id=team_id).count()
        if current_members >= team.max_members:
            raise ValidationError({'error': '团队已满'})
            
        # 创建成员
        member = TeamMember.objects.create(
            team_id=team_id,
            user_id=user_id,
            role='member'
        )
        
        serializer = TeamMemberSerializer(member)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def delete(self, request, team_id, member_id):
        """移除团队成员"""
        try:
            member = TeamMember.objects.get(
                team_id=team_id,
                id=member_id
            )
            member.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except TeamMember.DoesNotExist:
            return Response(
                {"error": "Member not found"}, 
                status=status.HTTP_404_NOT_FOUND
            )

class TeamSprintView(APIView):
    permission_classes = []

    def get(self, request, team_id):
        """获取冲刺数据和排行"""
        try:
            team = Team.objects.get(id=team_id)
            current_sprint = TeamSprint.objects.filter(
                team=team,
                status='ongoing'
            ).first()
            
            # 获取成员排行
            rankings = []
            if current_sprint:
                rankings = SprintRecord.objects.filter(
                    sprint=current_sprint
                ).values(
                    'member__user__username'
                ).annotate(
                    total_hours=models.Sum('study_hours')
                ).order_by('-total_hours')[:10]  # 只取前10名
                
                # 格式化排行数据
                rankings = [{
                    'username': rank['member__user__username'],
                    'total_hours': round(rank['total_hours'], 1),
                    'avatar': f"https://api.dicebear.com/7.x/avataaars/svg?seed={rank['member__user__username']}"
                } for rank in rankings]
            
            # 获取学习动态
            activities = []
            if current_sprint:
                records = SprintRecord.objects.filter(
                    sprint=current_sprint
                ).select_related('member__user').order_by('-created_at')[:10]
                
                for record in records:
                    activities.append({
                        'id': record.id,
                        'username': record.member.user.username,
                        'avatar': f"https://api.dicebear.com/7.x/avataaars/svg?seed={record.member.user.username}",
                        'content': f'完成学习 {record.study_hours} 小时',
                        'time': record.created_at.strftime('%Y-%m-%d %H:%M:%S')
                    })
            
            return Response({
                'sprint_id': current_sprint.id if current_sprint else None,
                'start_time': current_sprint.start_time if current_sprint else None,
                'target_hours': current_sprint.target_hours if current_sprint else 0,
                'completed_hours': current_sprint.completed_hours if current_sprint else 0,
                'rankings': rankings,
                'activities': activities
            })
        except Team.DoesNotExist:
            return Response({'error': '团队不存在'}, status=404)
        except Exception as e:
            return Response({'error': str(e)}, status=500)

    def post(self, request, team_id):
        """开始冲刺"""
        try:
            team = Team.objects.get(id=team_id)
            target_hours = float(request.data.get('target_hours', 20))
            
            # 创建新的冲刺
            sprint = TeamSprint.objects.create(
                team=team,
                target_hours=target_hours
            )
            
            return Response({
                'message': '冲刺开始',
                'sprint_id': sprint.id,
                'target_hours': target_hours
            })
        except Team.DoesNotExist:
            return Response({'error': '团队不存在'}, status=404)

    def put(self, request, team_id):
        """更新冲刺进度"""
        sprint = TeamSprint.objects.get(
            team_id=team_id,
            status='ongoing'
        )
        member = TeamMember.objects.get(
            team_id=team_id,
            user_id=request.data.get('user_id')
        )
        
        # 记录学习时长
        SprintRecord.objects.create(
            sprint=sprint,
            member=member,
            study_hours=request.data.get('hours', 0)
        )
        
        # 更新总时长
        sprint.completed_hours += request.data.get('hours', 0)
        sprint.save()
        
        # 更新团队统计
        team = Team.objects.get(id=team_id)
        team.total_hours += request.data.get('hours', 0)
        team.progress = min(100, int(sprint.completed_hours / sprint.target_hours * 100))
        team.save()
        
        return Response({'message': '进度已更新'})

class TeamDetailView(APIView):
    """团队详情视图"""
    permission_classes = []

    def get(self, request, team_id):
        """获取团队详情"""
        try:
            team = Team.objects.get(id=team_id)
            serializer = TeamSerializer(team)
            return Response(serializer.data)
        except Team.DoesNotExist:
            return Response(
                {'error': '团队不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

class TeamTaskView(APIView):
    """团队任务视图"""
    permission_classes = []

    def get(self, request, team_id):
        """获取团队任务列表"""
        tasks = TeamTask.objects.filter(team_id=team_id)
        return Response([{
            'id': task.id,
            'title': task.title,
            'description': task.description,
            'status': task.status,
            'created_at': task.created_at
        } for task in tasks])

    def post(self, request, team_id):
        """创建团队任务"""
        try:
            team = Team.objects.get(id=team_id)
            task = TeamTask.objects.create(
                team=team,
                title=request.data.get('title'),
                description=request.data.get('description', '')
            )
            return Response({
                'id': task.id,
                'title': task.title,
                'description': task.description,
                'status': task.status,
                'created_at': task.created_at
            }, status=status.HTTP_201_CREATED)
        except Team.DoesNotExist:
            return Response(
                {'error': '团队不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

    def put(self, request, team_id, task_id):
        """完成任务"""
        try:
            task = TeamTask.objects.get(
                team_id=team_id,
                id=task_id,
                status='pending'
            )
            task.status = 'completed'
            task.completed_at = timezone.now()
            task.save()

            # 更新团队完成任务数
            team = task.team
            team.completed_tasks += 1
            team.save()
            # 更新冲刺的完成学时
            sprint = TeamSprint.objects.filter(team_id=team_id, status='ongoing').first()
            if sprint:
                sprint.completed_hours += 1  # 你可以根据任务的实际学时来更新
                sprint.save()

            # 更新团队完成任务数
            team = task.team
            team.completed_tasks += 1
            team.save()
            return Response({
                'message': '任务已完成'
            })
        except TeamTask.DoesNotExist:
            return Response(
                {'error': '任务不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

class TeamRankingView(APIView):
    permission_classes = []

    def get(self, request):
        """获取团队排行榜"""
        try:
            # 获取所有团队的排名
            rankings = TeamRanking.objects.all()[:10]  # 只返回前10名
            serializer = TeamRankingSerializer(rankings, many=True)
            return Response(serializer.data)
        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def post(self, request):
        """更新团队排名"""
        try:
            team_id = request.data.get('team_id')
            score = request.data.get('score', 0)
            sprint_count = request.data.get('sprint_count', 0)
            total_hours = request.data.get('total_hours', 0)

            ranking, created = TeamRanking.objects.get_or_create(
                team_id=team_id,
                defaults={
                    'score': score,
                    'sprint_count': sprint_count,
                    'total_hours': total_hours
                }
            )

            if not created:
                ranking.score = score
                ranking.sprint_count = sprint_count
                ranking.total_hours = total_hours
                ranking.save()

            return Response(TeamRankingSerializer(ranking).data)
        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
